package com.example.camerastudy.slice;

import com.example.camerastudy.ResourceTable;
import com.example.camerastudy.component.CameraView;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class CameraSlice extends AbilitySlice {

    private CameraView cameraView;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_camera_view);

        getWindow().setTransparent(true);

        cameraView = (CameraView) findComponentById(ResourceTable.Id_cameraView);

        cameraView.setImageDataCallback(bytes -> {
            File desFile = new File(getCacheDir(), "test_" + System.currentTimeMillis() + ".jpg");
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(desFile);
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        cameraView.startPreview();

        findComponentById(ResourceTable.Id_button_capture).setClickedListener(component -> {
            cameraView.takePicture();
        });

        findComponentById(ResourceTable.Id_button_multi_capture).setClickedListener(component -> {
            cameraView.takeMultiPicture();
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        cameraView.onStop();
    }
}
